package com.xcjh.module_ad.activity

import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.ViewGroup
import android.webkit.*
import android.widget.LinearLayout
import androidx.annotation.RequiresApi
import com.google.android.gms.ads.*
import com.google.android.gms.ads.initialization.InitializationStatus
import com.google.android.gms.ads.interstitial.InterstitialAd
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback
import com.google.android.gms.ads.rewarded.RewardedAd
import com.google.android.gms.ads.rewarded.RewardedAdLoadCallback
import com.google.gson.Gson
import com.just.agentweb.AgentWeb
import com.just.agentweb.WebChromeClient
import com.xcjh.base_lib.base.activity.BaseActivity
import com.xcjh.base_lib.utils.loge
import com.xcjh.module_ad.SplashActivity
import com.xcjh.module_ad.databinding.AdActivityAdmobBinding

/**
 * admob google广告联盟
 */
class AdmobActivity : BaseActivity() {
    private lateinit var binding: AdActivityAdmobBinding
    private var mInterstitialAd: InterstitialAd? = null
    private var mRewardedAd: RewardedAd? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = AdActivityAdmobBinding.inflate(layoutInflater)
        setContentView(binding.root)
        initAd()
    }

    //加载广告
    @SuppressLint("SetJavaScriptEnabled")
    private fun initAd() {
        //初始化google admob广告联盟
        MobileAds.initialize(this) { initializationStatus: InitializationStatus? ->
            Gson().toJson(initializationStatus).loge("MobileAds.initialize====")
        }
        initLunchAd()
        initInterstitialAd()
        initRewardVideoAd()
        initNativeAd()
        initWeb()
        //开屏广告
        binding.btnLunch.setOnClickListener {
            startMyActivity<SplashActivity>()
        }
        //插页广告
        binding.btnInterstitial.setOnClickListener {
            showInterst()
        }
        //激励视频广告
        binding.btnRewardVideo.setOnClickListener {
            showReward()
        }
        //原生广告
        binding.btnNative.setOnClickListener {
            startMyActivity<AdNativeActivity>()
        }
    }

    private fun showReward() {
        val TAG = "激励视频广告"
        if (mRewardedAd != null) {
            mRewardedAd?.fullScreenContentCallback = object : FullScreenContentCallback() {
                override fun onAdShowedFullScreenContent() {
                    "开始显示广告".loge("$TAG====")
                }

                override fun onAdFailedToShowFullScreenContent(adError: AdError) {
                    "广告展示失败".loge("$TAG====")
                    mRewardedAd = null
                    initRewardVideoAd()
                }

                override fun onAdDismissedFullScreenContent() {
                    "隐藏广告".loge("$TAG====")
                    mRewardedAd = null
                    initRewardVideoAd()
                }

                override fun onAdClicked() {
                    // 被点击时调用
                    "广告被点击".loge("$TAG====")
                }
            }
            mRewardedAd?.show(this, OnUserEarnedRewardListener { rewardItem -> //  用户获得奖励回调.
                // 奖励的金额
                val rewardAmount = rewardItem.amount
                // 奖励的类型
                val rewardType = rewardItem.type
                Log.d("TAG", "===222用户获得奖励回调.===$rewardType==金额==$rewardAmount")
            })

        } else {
            Log.d(TAG, "广告尚未准备好.")
            initRewardVideoAd()
        }
    }

    private fun showInterst() {
        val TAG = "插屏广告"
        if (mInterstitialAd != null) {
            mInterstitialAd?.fullScreenContentCallback =
                object : FullScreenContentCallback() {
                    override fun onAdShowedFullScreenContent() {
                        Log.e(TAG, "开始显示广告.")
                    }

                    override fun onAdFailedToShowFullScreenContent(adError: AdError) {
                        Log.e(TAG, "广告展示失败.")
                        mInterstitialAd = null
                        initInterstitialAd()
                    }

                    override fun onAdDismissedFullScreenContent() {
                        Log.e(TAG, "隐藏广告")
                        mInterstitialAd = null
                        initInterstitialAd()
                    }

                    override fun onAdClicked() {
                        super.onAdClicked()
                        // 被点击时调用
                        Log.e(TAG, "===广告onAdClicked")
                    }
                }
            mInterstitialAd?.show(this)
        } else {
            Log.d(TAG, "广告尚未准备好.")
            initInterstitialAd()
        }
    }

    private lateinit var agentWeb: AgentWeb
    private fun initWeb() {
        agentWeb = AgentWeb.with(this)
            .setAgentWebParent(
                binding.agentWeb as ViewGroup,
                LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT
                )
            )
            .closeIndicator()
            .setWebChromeClient(object : WebChromeClient() {
                override fun onProgressChanged(view: WebView?, newProgress: Int) {
                    super.onProgressChanged(view, newProgress)
                }
            })
            .setWebViewClient(object : com.just.agentweb.WebViewClient() {
                override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                    super.onPageStarted(view, url, favicon)
                    Log.e("TAG", "===-----onPageStarted------ $url")
                }

                @RequiresApi(Build.VERSION_CODES.M)
                override fun onReceivedError(
                    view: WebView?,
                    request: WebResourceRequest?,
                    error: WebResourceError?
                ) {
                    super.onReceivedError(view, request, error)
                    Log.e("TAG", "===-----onReceivedError------ " + error?.description.toString())
                }

                override fun onPageFinished(view: WebView?, url: String?) {
                    super.onPageFinished(view, url)
                    Log.e("TAG", "===-----onPageFinished------ ")
                }
            })
            // .setWebView(binding.agentWeb)
            .createAgentWeb()
            .ready().get()
        agentWeb.urlLoader.loadUrl("https://music.163.com/")
        // .go("https://music.163.com/")
    }

    override fun onPause() {
        "onPause".loge("===")
        agentWeb.webCreator.webView.onPause()
        // agentWeb.webLifeCycle.onPause() //暂停应用内所有WebView ， 调用mWebView.resumeTimers();/mAgentWeb.getWebLifeCycle().onResume(); 恢复。
        super.onPause()
    }

    override fun onResume() {
        "onResume".loge("===")
        agentWeb.webLifeCycle.onResume()
        super.onResume()
    }

    //开屏广告
    private fun initLunchAd() {
        //ca-app-pub-3940256099942544/3419835294

    }

    private fun initInterstitialAd() {
        val TAG = "插屏广告"
        //插页式激励广告
        InterstitialAd.load(
            this,
            "ca-app-pub-3940256099942544/1033173712",
            AdRequest.Builder().build(),
            object : InterstitialAdLoadCallback() {
                override fun onAdLoaded(interstitialAd: InterstitialAd) {
                    // The mInterstitialAd reference will be null until
                    // an ad is loaded.
                    mInterstitialAd = interstitialAd
                    Log.e(TAG, "广告已加载")

                }

                override fun onAdFailedToLoad(loadAdError: LoadAdError) {
                    mInterstitialAd = null
                    //initInterstitialAd()
                    val error = String.format(
                        "广告处理错误==domain: %s, code: %d, message: %s",
                        loadAdError.domain,
                        loadAdError.code,
                        loadAdError.message
                    )
                    Log.e(TAG, error)
                }
            })

    }

    private fun initRewardVideoAd() {
        val TAG = "激励视频广告"
        RewardedAd.load(
            this,
            "ca-app-pub-3940256099942544/5224354917",
            AdRequest.Builder().build(),
            object : RewardedAdLoadCallback() {
                override fun onAdLoaded(rewardedAd: RewardedAd) {
                    mRewardedAd = rewardedAd
                    "广告已加载".loge("$TAG====")

                }

                override fun onAdFailedToLoad(loadAdError: LoadAdError) {
                    mRewardedAd = null
                    //initRewardVideoAd()
                    val error = String.format(
                        "广告处理错误==domain: %s, code: %d, message: %s",
                        loadAdError.domain,
                        loadAdError.code,
                        loadAdError.message
                    )
                    error.loge("$TAG====")
                }
            })

    }

    private fun initNativeAd() {


    }

}